package quickmall

import grails.converters.JSON
import groovy.json.JsonSlurper

import java.util.List;

class RestController {

	def getrest () {
		System.out.println("testes");
		System.out.println("existe " + Offer.exists(params.id))
		System.out.println("Offer.get(params.id) " + Offer.get(params.id))
			
		if(params.id && Offer.exists(params.id)) {
			Offer o = Offer.get(params.id)
			def result = parseOffer(o)
			render result as JSON
		}
		else {
			def all = parseAllOffers(Offer.list())
			render all as JSON
		}
	}
	
	private Object parseOffer(Offer o){
		def slurper = new JsonSlurper()
		def result = slurper.parseText('{\"id\":'+o.id+',\"active\":'+o.active+',\"description\":\"'+o.description+'\",\"store\":{\"name\":\"'+o.store.name+'\"}}')
		return result
	}
	
	private List<Object> parseAllOffers(List<Offer> offers){
		List<Object> objts = new ArrayList<Object>();
		for (Offer o : offers) {
			objts.add(parseOffer(o))
		}
		return objts
	}
    def index() { }
}
